﻿#include "ImageLabel.h"
#include <QDebug>
#include <string.h>

ImageLabel::ImageLabel(QWidget *parent):QLabel (parent)
    ,m_zoomValue(1.0)
    ,m_xPtInterval(0)
    ,m_yPtInterval(0)
    ,m_isPressed(false)
    ,mIsLoadingImage(false)
{
}

void ImageLabel::paintEvent(QPaintEvent *event)
{
    if(mIsLoadingImage)
        return;
    QPainter painter(this);
    if (!m_image.isNull()){
        // 根据窗口计算应该显示的图片的大小
        int width = qMin(m_image.width(), this->width());
        int height = width * 1.0 / (m_image.width() * 1.0 / m_image.height());
        height = qMin(height, this->height());
        width = height * 1.0 * (m_image.width() * 1.0 / m_image.height());
        // 平移
        painter.translate(this->width() / 2 + m_xPtInterval, this->height() / 2 + m_yPtInterval);
        // 缩放
        painter.scale(m_zoomValue, m_zoomValue);//垂直水平两个方向
        // 绘制图像
        QRect picRect(-width / 2, -height / 2, width, height);
        painter.drawPixmap(picRect, QPixmap::fromImage(m_image));
    }
}

void ImageLabel::wheelEvent(QWheelEvent *event)
{
#if QT_VERSION >= 0x060000
// Qt 6 的代码
    int value = event->angleDelta().y();
#else
    // Qt 5 的代码
    int value = event->delta();
#endif
    if (value > 0)  //放大
        OnZoomInImage();
    else            //缩小
        OnZoomOutImage();

    update();
}

void ImageLabel::mousePressEvent(QMouseEvent *event)
{
    //记录初始坐标
    m_oldPos = event->pos();
    m_isPressed = true;
}

void ImageLabel::mouseMoveEvent(QMouseEvent *event)
{
    if (!m_isPressed)
        return QWidget::mouseMoveEvent(event);

    setCursor(Qt::SizeAllCursor);
    QPoint pos = event->pos();
    int xPtInterval = pos.x() - m_oldPos.x();
    int yPtInterval = pos.y() - m_oldPos.y();

    m_xPtInterval += xPtInterval;
    m_yPtInterval += yPtInterval;

    m_oldPos = pos;
    update();
}

void ImageLabel::mouseReleaseEvent(QMouseEvent *event)
{
    m_isPressed = false;
    setCursor(Qt::ArrowCursor);
}

void ImageLabel::OnLoadImage(QImage image, double scale)
{
    if(image.isNull())
        return;
    mIsLoadingImage = true;
    m_isPressed = false;
    if(image.format() == QImage::Format_Indexed8){
        m_image = image.convertToFormat(QImage::Format_RGB888);
    } else {
        m_image = image;
    }
    mIsLoadingImage = false;
    update();
}

void ImageLabel::OnZoomInImage()
{
    m_zoomValue += 0.15;
    update();
}

void ImageLabel::OnZoomOutImage()
{
    m_zoomValue -= 0.15;
    if (m_zoomValue <= 0){
        m_zoomValue = 0.15;
        return;
    }

    update();
}

void ImageLabel::OnPresetImage()
{
    m_zoomValue = 1.0;
    m_xPtInterval = 0;
    m_yPtInterval = 0;
    update();
}


